import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    products: [
      { id: 1, name: '篮球', price: 20, quantity: 0 },
      { id: 2, name: '足球', price: 20, quantity: 0 },
      { id: 3, name: 'iPhone 15 promax 1TB 暗紫色', price: 15000, quantity: 0 }
    ]
  },
  mutations: {
    increment(state, id) {
      const product = state.products.find(p => p.id === id)
      product.quantity++
    },
    decrement(state, id) {
      const product = state.products.find(p => p.id === id)
      if (product.quantity > 0) {
        product.quantity--
      }
    }
  },
  actions: {
    addToCart({ commit }, id) {
      commit('increment', id)
    },
    removeFromCart({ commit }, id) {
      commit('decrement', id)
    }
  },
  getters: {
    total(state) {
      return state.products.reduce((total, product) => {
        return total + (product.price * product.quantity)
      }, 0)
    }
  },
  modules: {
  }
})
